package com.chenqi.tool.ext;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * author：陈奇
 * Date：2020-06-03
 * Description：
 */
public class GsonUtils {

    /**
     * 转成bean
     *
     * @return
     */
    public static String GsonToJson(Object object) {
        Gson gson = new Gson();
        return gson.toJson(object);
    }

    /**
     * 转成bean
     *
     * @param str
     * @param cls
     * @return
     */
    public static <T> T GsonToBean(String str, Class<T> cls) {
        Gson gson = new Gson();
        return gson.fromJson(str, cls);
    }

    /**
     * 转成bean
     *
     * @param str
     * @return
     */
    public static <T> T GsonToBeans(String str) {
        Gson gson = new Gson();
        return gson.fromJson(str, new TypeToken<T>() {
        }.getType());
    }

    /**
     * 转成list
     *
     * @param jsonString
     * @param cls
     * @return
     */
    public static <T> List<T> GsonToList(String jsonString, Class<T> cls) {
        List<T> list = new ArrayList<T>();
        try {
            Gson gson = new Gson();
            JsonArray arry = new JsonParser().parse(jsonString).getAsJsonArray();
            for (JsonElement jsonElement : arry) {
                list.add(gson.fromJson(jsonElement, cls));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }

    public static Map<String, Object> GsonToMap(String jsonString) {
        Map<String, Object> map = new HashMap<>();
        try {
            Gson gson = new Gson();
            map = gson.fromJson(jsonString, new TypeToken<Map<String, Object>>() {
            }.getType());
        } catch (Exception e) {
            e.printStackTrace();
        }

        return map;
    }
}
